//
//  HomeVC.m
//  phmall
//
//  Created by admin on 2017/9/23.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "HomeVC.h"
#import "HomeGoodsCell.h"
#import "SeckillView.h"
#import "HomeListModel.h"
#import "GoodsModel.h"
#import "PageViewController.h"
#import "SearchVC.h"
#import "GroupBuyingVC.h"
#import "GoodsClassifyVC.h"
#import "CommodityDetailsVC.h"
#import "ClassPageVC.h"
#import "HomeDiscountVIew.h"
#import "DynamicVC.h"
#import "CountDownView.h"
//#import "MessageViewController.h"
#import "CouponPageVC.h"
#import "AuctionViewController.h"
#import "BrandPageVC.h"
#import "IntegralStorePageVC.h"
#import "SpecialViewController.h"
#import "FUIImageView.h"
#import "HotNewsPageVC.h"
#import "SeckillDetailsVC.h"
#import "UserInfoModel.h"
#import "AdvertisingCell.h"
@interface HomeVC ()<UICollectionViewDelegate,UICollectionViewDataSource,SDCycleScrollViewDelegate,UIWebViewDelegate,HomeGoodsCellDelegate,CountDownViewDelegate,HomeDiscountVIewDelegate,SeckillViewDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate,UITabBarControllerDelegate>{
    CGFloat     height;
    UIView      *head;
    NSString    *alpha;
    HomeDiscountVIew *discount;
    HomeDiscountVIew *discount2;
    FUIImageView      *seachV;
    UIBarButtonItem  *cut;
//    UIBarButtonItem  *rightBar;
    UIBarButtonItem  *leftBar;
}
@property(nonatomic,strong)MBProgressHUD     *hud;
@property(nonatomic,strong)UICollectionView  *collectionView;
@property(nonatomic,strong)SDCycleScrollView *scrollView;
@property(nonatomic,strong)SDCycleScrollView *textCycle;
@property(nonatomic,strong)NSMutableArray    *infoArr;
@property(nonatomic,strong)NSMutableArray    *adverArr;
@property(nonatomic,strong)HomeListModel     *model;
@property(nonatomic,strong)NSMutableArray    *onsale;
@end

@implementation HomeVC
-(void)moreAction{
    self.hidesBottomBarWhenPushed=YES;
    self.navigationController.navigationBar.clipsToBounds =YES;
    PageViewController *page=[[PageViewController alloc]init];
    [self.navigationController pushViewController:page animated:YES];
    self.hidesBottomBarWhenPushed=NO;

}
-(void)didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    self.hidesBottomBarWhenPushed=YES;
    SeckillDetailsVC *class=[[SeckillDetailsVC alloc] init];
    [self.navigationController pushViewController:class animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}
-(void)selectIndex:(UIButton *)sender{
    NSInteger index=sender.tag-300;
    self.hidesBottomBarWhenPushed=YES;
    ClassPageVC *class=[[ClassPageVC alloc] init];
    class.index=index;
    [self.navigationController pushViewController:class animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}
-(void)setSelectAtIndex:(NSInteger)index{
    self.hidesBottomBarWhenPushed=YES;
    ClassPageVC *class=[[ClassPageVC alloc] init];
    class.index=index;
    [self.navigationController pushViewController:class animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}


// 按钮点击事件
-(void)switchTheLanguage{
    //修改本地获取的语言文件-交替
    NSString *language = [[NSUserDefaults standardUserDefaults]objectForKey:@"appLanguage"];
    
    if ([language isEqualToString: @"en"]) {
        
        [[NSUserDefaults standardUserDefaults] setObject:@"zh-Hans" forKey:@"appLanguage"];
        
    }else {
        
        [[NSUserDefaults standardUserDefaults] setObject:@"en" forKey:@"appLanguage"];
    }
    
    [[NSUserDefaults standardUserDefaults] synchronize];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeLanguage" object:nil];
}


-(void)rightBarAction{
    
//    if ([[EMClient sharedClient] isAutoLogin]) {
//        self.hidesBottomBarWhenPushed=YES;
//        MessageViewController *chat=[[MessageViewController alloc] init];
//        [self.navigationController pushViewController:chat animated:YES];
//        self.hidesBottomBarWhenPushed=NO;
//    }else{
//        [self whetherLogin];
//    }
    
    
}
-(void)leftBarAction{

}
-(void)integralStoreTapAction{
    self.hidesBottomBarWhenPushed=YES;
    IntegralStorePageVC *sear=[[IntegralStorePageVC alloc] init];
    [self.navigationController pushViewController:sear animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}
-(void)groupBuyingTapAction{
    self.hidesBottomBarWhenPushed=YES;
    GroupBuyingVC *sear=[[GroupBuyingVC alloc] init];
    [self.navigationController pushViewController:sear animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}
-(void)specialTapAction{
    self.hidesBottomBarWhenPushed=YES;
    SpecialViewController *sear=[[SpecialViewController alloc] init];
    [self.navigationController pushViewController:sear animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}
-(void)couponTapAction{
    self.hidesBottomBarWhenPushed=YES;
    CouponPageVC *sear=[[CouponPageVC alloc] init];
    [self.navigationController pushViewController:sear animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}
-(void)auctionTapAction{
    self.hidesBottomBarWhenPushed=YES;
    AuctionViewController *sear=[[AuctionViewController alloc] init];
    [self.navigationController pushViewController:sear animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}
-(void)brandTapAction{
    self.hidesBottomBarWhenPushed=YES;
    BrandPageVC *sear=[[BrandPageVC alloc] init];
    [self.navigationController pushViewController:sear animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}
-(void)moreAction:(UICollectionViewCell *)cell{
    for (int i=0; i<self.infoArr.count; i++) {
        NSIndexPath *index1 =  [NSIndexPath indexPathForItem:i inSection:0];
        HomeGoodsCell *goodsCell=(HomeGoodsCell *)[self.collectionView cellForItemAtIndexPath:index1];
        if (cell!=goodsCell) {
            [goodsCell moreViewTapAction];
        }
    }
}
-(void)seachTapAction{
    self.hidesBottomBarWhenPushed=YES;
    SearchVC *sear=[[SearchVC alloc] init];
    [self.navigationController pushViewController:sear animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}
-(void)selectAtImage:(UIView *)view andIndex:(NSInteger)index{
//    NSLog(@"%ld----%ld",(long)index,(long)view.tag);
    if (view.tag==200) {
        switch (index) {
            case 1:
                
                break;
            case 2:
                [self groupBuyingTapAction];
                break;
            case 3:
                [self auctionTapAction];
                break;
            case 4:
                 [self integralStoreTapAction];
                break;
            default:
                break;
        }
    }else{
        switch (index) {
            case 1:
//                [self brandTapAction];
                break;
            case 2:
                [self brandTapAction];
                break;
            case 3:
                [self specialTapAction];
                break;
            case 4:
                [self couponTapAction];
                break;
            default:
                break;
        }
    }
}
- (void)changeLanguage
{
    // 我们要把系统windown的rootViewController替换掉
    TabBarVController *tab = [[TabBarVController alloc] init];
    [UIApplication sharedApplication].keyWindow.rootViewController = tab;
    
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:Localized(@"语言切换") message:Localized(@"切换成功") delegate:self cancelButtonTitle:Localized(@"确定") otherButtonTitles:nil, nil];
    [alert show];
}

//-(void)message;sDidReceive:(NSArray *)aMessages{
//    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
//
//    NSInteger unreadCount = 0;
//
//    for (EMConversation *conversation in conversations) {
//
//        unreadCount += conversation.unreadMessagesCount;
//
//    }
//}
-(void)HeaderRefresh{
    [self loadDataWithIndex];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeLanguage) name:@"changeLanguage" object:nil];
//    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
    self.navBarBgAlpha=alpha;
    // 设置子类的NavBar上的渲染颜色
    self.navigationController.navigationBar.tintColor = [UIColor clearColor];
    // 改变NavBar底层View的颜色
    self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];
    // 改变NavBar顶层View的颜色
    self.navigationController.navigationBar.barTintColor = [UIColor orangeColor];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self loadDataWithInfo];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadDataWithIndex];
    [self loadDataWithCategory];
    
    self.navigationController.tabBarController.delegate=self;
    
    //搜索框
    seachV = [[FUIImageView alloc] initWithFrame:CGRectZero];
    seachV.contentMode= UIViewContentModeScaleAspectFit;
    
    seachV.backgroundColor=[UIColor whiteColor];
    seachV.layer.cornerRadius = 5;
    seachV.userInteractionEnabled=YES;
    seachV.image=[UIImage imageNamed:@"搜索背景"];
    seachV.layer.masksToBounds=YES;
    self.navigationItem.titleView=seachV;
    
    if (IS_IOS_VERSION_11) {
        [seachV mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.offset(0);
            make.centerY.offset(0);
            make.height.offset(30);
        }];
    }
    
    
    YYCache *cache = [YYCache cacheWithName:@"home"];
    if ([cache containsObjectForKey:@"index"]) {
        NSMutableDictionary *index = (NSMutableDictionary *)[cache objectForKey:@"index"];
        NSLog(@"%@",index);
        [self analysisDataWithIndexDictionary:index];
        [self getupHeaderView];
        [self.collectionView reloadData];
    }

    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(seachTapAction)];
    tapGesture.numberOfTapsRequired = 1;
    [seachV addGestureRecognizer:tapGesture];
    
    UIImageView *seach=[[UIImageView alloc]init];
    [seachV addSubview:seach];
    seach.image=[UIImage imageNamed:@"搜索"];
    seach.backgroundColor=[UIColor whiteColor];
    [seach mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(seachV).offset(10);
        make.height.width.offset(14);
        make.centerY.equalTo(seachV);
    }];
    //
    UILabel *seachText=[[UILabel alloc]init];
    seachText.text=Localized(@"输入关键词");
    //    seachText.textColor=[UIColor groupTableViewBackgroundColor];
    seachText.font=[UIFont systemFontOfSize:13];
    [seachV addSubview:seachText];
    [seachText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(seach.mas_right).offset(5);
        make.height.offset(30);
        make.centerY.equalTo(seachV);
    }];
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(HeaderRefresh)];
    self.navBarBgAlpha=alpha=@"0.0";


    cut=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"中英文"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(switchTheLanguage)];
//    rightBar=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"消息"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarAction)];

    self.navigationItem.rightBarButtonItem= cut;
    
    leftBar=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"PHMALL"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(leftBarAction)];

    self.navigationItem.leftBarButtonItem=leftBar;
    self.emptyType=EmptyDataSetNone;
    [self.view addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(-(STATUS_BAR_HEIGHT+44));
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view).with.offset(0);
    }];
    
}
//首页数据
- (void)loadDataWithIndex{
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"index"];
    [httpTool ZBPostNetDataWith:urlstr withDic:nil andSuccess:^(id responseObject) {
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([responseDict[@"ret"] isEqualToString:@"200"]) {
            YYCache *cache = [YYCache cacheWithName:@"home"];
            [cache setObject:responseDict[@"data"] forKey:@"index"];
            [self analysisDataWithIndexDictionary:responseDict[@"data"]];
        }
        [self loadDataWithOnsale];
    } andFailure:^{
        [self.hud hideAnimated:YES];
        if (self.emptyType==EmptyDataSetNoNetwork) {
            [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2];
        }
        [self.collectionView.mj_header endRefreshing];
        self.emptyType=EmptyDataSetNoNetwork;
        [self.collectionView reloadData];
    }];
}
- (void)analysisDataWithIndexDictionary:(NSDictionary*)dictionary{
    [self.infoArr removeAllObjects];
    self.model = [HomeListModel yy_modelWithDictionary:dictionary];
    for (HomeGoodsModel *sModel in self.model.default_wap_hot_shop) {
        [self.infoArr addObject:sModel];
    }
    for (DefaultModel *model in self.model.default_wap_ad_2) {
        [self.adverArr addObject:model];
    }
}
//秒杀
- (void)loadDataWithOnsale{
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"get_onsale"];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
  
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([responseDict[@"ret"] isEqualToString:@"200"]) {
            if (responseDict[@"data"] ==[NSNull alloc]) {
                [self analysisDataWithOnsaleArray:responseDict[@"data"]];
            }
        }
        [self.hud hideAnimated:YES];
        [self getupHeaderView];
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView reloadData];
    } andFailure:^{
        [self.hud hideAnimated:YES];
        if (self.emptyType==EmptyDataSetNoNetwork) {
            [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2];
        }
        [self.collectionView.mj_header endRefreshing];
        self.emptyType=EmptyDataSetNoNetwork;
        [self.collectionView reloadData];
    }];
}
- (void)analysisDataWithOnsaleArray:(NSMutableArray *)array{
    [self.onsale removeAllObjects];
    for (NSDictionary *dict in array) {
        GoodsModel *model = [GoodsModel yy_modelWithDictionary:dict];
        [self.onsale addObject:model];
    }

}

- (void)loadDataWithCategory{
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"category"];
    //   NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [httpTool ZBPostNetDataWith:urlstr withDic:nil andSuccess:^(id responseObject) {
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([responseDict[@"ret"] isEqualToString:@"200"]) {
            YYCache *cache = [YYCache cacheWithName:@"category"];
            [cache setObject:responseDict[@"data"] forKey:@"name"];
        }
    } andFailure:^{
       
    }];
}



- (void)loadDataWithInfo{
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"member_index/get_member_info"];
    [httpTool ZBPostNetDataWith:urlstr withDic:nil andSuccess:^(id responseObject) {
        NSMutableDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([response[@"ret"] isEqualToString:@"200"]) {
            [self analysisDataWithMemberInfoDictionary:response[@"data"][0]];
        }
    } andFailure:^{
        [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2];
        //[SVProgressHUD showErrorWithStatus:@"网络错误"];
    }];
}
- (void)analysisDataWithMemberInfoDictionary:(NSDictionary*)dictionary{
//    UserInfoModel *model = [UserInfoModel yy_modelWithDictionary:dictionary];
    
    YYCache *cache = [YYCache cacheWithName:@"user"];
    [cache setObject:dictionary forKey:@"userInfo"];
}
#pragma mark collectionView代理方法

//返回section个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

//每个section的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.infoArr.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId=@"cell";
    HomeGoodsCell *cell = (HomeGoodsCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
    cell.model=self.infoArr[indexPath.row];
    cell.delegate =self;
    ViewBorderRadius(cell, 10, 0, [UIColor clearColor]);
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
//    [self getupHeaderView];
    return CGSizeMake(SCREEN_WIDTH, height);
}
//设置每个item的尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (iPhone5SE) {
        return CGSizeMake(SCREEN_WIDTH/2-15, 230);
    }else  if (iPhone6_6s) {
        return CGSizeMake(SCREEN_WIDTH/2-15, 252);
    }else  if (iPhone6Plus_6sPlus) {
        return CGSizeMake(SCREEN_WIDTH/2-15, 272);
    }else{
        return CGSizeMake(SCREEN_WIDTH/2-15, 252);
    }
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    for (int i=0; i<self.infoArr.count; i++) {
        NSIndexPath *index1 =  [NSIndexPath indexPathForItem:i inSection:0];
        HomeGoodsCell *cell =  (HomeGoodsCell *)[_collectionView cellForItemAtIndexPath:index1];
        [cell moreViewTapAction];
    }
    HomeGoodsModel *model=self.infoArr[indexPath.row];
    self.hidesBottomBarWhenPushed=YES;
    CommodityDetailsVC *deta=[[CommodityDetailsVC alloc] init];
    deta.uid=model.goods_id;
    [self.navigationController pushViewController:deta animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}
//设置每个item水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}
 //设置每个item垂直间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
        return UIEdgeInsetsMake(0, 10, 10, 10);
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableView" forIndexPath:indexPath];
    if (headerView.subviews.count>0) {
        return headerView;
    }
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        headerView.backgroundColor=[UIColor groupTableViewBackgroundColor];
        [headerView addSubview:head];
        [head mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.equalTo(headerView);
            make.height.offset(height);
        }];
        [head layoutIfNeeded];
        return headerView;
    }
    return headerView;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView.contentOffset.y>=0 ) {
        if (scrollView.contentOffset.y<=(STATUS_BAR_HEIGHT+44)) {
            self.navBarBgAlpha=alpha=[NSString stringWithFormat:@"%f",scrollView.contentOffset.y/(STATUS_BAR_HEIGHT+44)];
        }else{
            self.navBarBgAlpha=alpha=@"1.0";
        }
        seachV.hidden=NO;
        [leftBar setImage:[[UIImage imageNamed:@"PHMALL"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
//        [rightBar setImage:[[UIImage imageNamed:@"消息"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
        [cut setImage:[[UIImage imageNamed:@"中英文"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
//        self.navigationItem.titleView.alpha=1;
    }else{
        self.navigationController.navigationBar.layer.shadowColor = [UIColor colorWithRed:0.00f green:0.00f blue:0.00f alpha:0].CGColor;
        seachV.hidden=YES;
        [leftBar setImage:[UIImage imageNamed:@"null"]];
        [cut setImage:[UIImage imageNamed:@"null"]];
//        [rightBar setImage:[UIImage imageNamed:@"null"]];
        self.navBarBgAlpha=alpha=@"0.0";

//        self.navigationItem.titleView.alpha=0;
        
    }
    for (int i=0; i<self.infoArr.count; i++) {
        NSIndexPath *index1 =  [NSIndexPath indexPathForItem:i inSection:0];
        HomeGoodsCell *cell =  (HomeGoodsCell *)[_collectionView cellForItemAtIndexPath:index1];
        [cell moreViewTapAction];
    }
}

- (void)getupHeaderView{
    head=[[UIView alloc]initWithFrame:CGRectZero];
    //轮播图
    _scrollView = [[SDCycleScrollView alloc] init];
    _scrollView.autoScrollTimeInterval=5;
    _scrollView.pageControlStyle=SDCycleScrollViewPageContolStyleClassic;
    _scrollView.pageControlDotSize=CGSizeMake(6, 6);
    _scrollView.bannerImageViewContentMode=UIViewContentModeRedraw;
    _scrollView.pageDotColor=[UIColor blackColor];
    _scrollView.placeholderImage= [UIImage imageNamed:@"图片空白页"];
    _scrollView.currentPageDotColor=[UIColor orangeColor];
    [head addSubview:_scrollView];
    _scrollView.delegate=self;
    [_scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(head).priorityHigh();
        make.left.equalTo(head).priorityHigh();
        make.right.equalTo(head).priorityHigh();
        make.height.offset(215).priorityHigh();
        
    }];
    [_scrollView layoutIfNeeded];
    NSMutableArray *cycle=[[NSMutableArray alloc] init];
    for (DefaultModel *sModel in self.model.default_wap_flash)
    {
         [cycle addObject:[NSString stringWithFormat:@"%@%@",IMGURL,sModel.pic]];
    }
    _scrollView.imageURLStringsGroup=cycle;
    _scrollView.bannerImageViewContentMode=UIViewContentModeScaleToFill;
    
    UIView *home=[[UIView alloc]init];
    [head addSubview:home];
    home.backgroundColor=[UIColor whiteColor];
    [home mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(head);
        make.top.equalTo(_scrollView.mas_bottom);
        make.height.offset(150);
    }];
    [home layoutIfNeeded];
    
    NSArray *menuArr=@[Localized(@"服装鞋包") ,Localized(@"美妆护理"),Localized(@"珠宝手表"),Localized(@"母婴玩具"),Localized(@"数码家电"),Localized(@"家居装修"),Localized(@"户外运动"),Localized(@"旅游度假"),Localized(@"吃喝玩乐"),Localized(@"更多分类")];
    
    NSArray *imageArr=@[@"服装鞋包",@"美妆护理",@"珠宝手表",@"母婴玩具",@"数码家电",@"家居装修",@"户外运动",@"旅游度假",@"吃喝玩乐",@"更多分类"];
    for (int i=0; i<menuArr.count; i++) {

        UIView *back=[[UIView alloc] init];
        [home addSubview:back];

        [back mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(home).with.offset(i/5*75);
            make.left.equalTo(home).with.offset(i%5*SCREEN_WIDTH/5);
            make.width.offset(SCREEN_WIDTH/5);
            make.height.offset(75);
        }];

        UIButton *but=[UIButton buttonWithType:UIButtonTypeCustom];
        [but setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [but setTitle:menuArr[i] forState:UIControlStateNormal];
        but.titleLabel.font=[UIFont systemFontOfSize:13];
        [but setImage:[UIImage imageNamed:imageArr[i]] forState:UIControlStateNormal];
        [back addSubview:but];
        but.tag=300+i;
        [but addTarget:self action:@selector(selectIndex:) forControlEvents:UIControlEventTouchUpInside];
        [but mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.bottom.equalTo(back);
        }];
        [but layoutIfNeeded];
        but.contentHorizontalAlignment=UIControlContentHorizontalAlignmentCenter;
        [but layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleTop imageTitleSpace:10];
    }

    
    UIView *messageView=[[UIView alloc]init];
    messageView.backgroundColor=[UIColor whiteColor];
    [head addSubview:messageView];
    [messageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(home.mas_bottom).with.offset(10);
        make.left.right.equalTo(head);
        make.height.offset(40);
        
    }];
    [messageView layoutIfNeeded];
    UIImageView *messageImg=[[UIImageView alloc]init];
    messageImg.image=[UIImage imageNamed:@"资讯热点"];
    [messageView addSubview:messageImg];
    [messageImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(messageView).offset(5);
        make.left.equalTo(messageView).offset(5);
        make.width.offset(40);
        make.height.offset(30);
    }];
    [messageImg layoutIfNeeded];
    self.textCycle = [SDCycleScrollView cycleScrollViewWithFrame:CGRectZero delegate:self placeholderImage:nil];
    self.textCycle.autoScrollTimeInterval=5;
    self.textCycle.titleLabelBackgroundColor=[UIColor clearColor];
    self.textCycle.scrollDirection = UICollectionViewScrollDirectionVertical;
    self.textCycle.onlyDisplayText = YES;
//    self.textCycle.titleLabelTextAlignment=NSTextAlignmentLeft;
    self.textCycle.titleLabelTextColor=[UIColor blackColor];
    self.textCycle.titleLabelTextFont=[UIFont systemFontOfSize:14];
//    self.textCycle.userInteractionEnabled=NO;
    [messageView addSubview:self.textCycle];
    [self.textCycle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(messageView).offset(10).priorityHigh();
        make.bottom.equalTo(messageView.mas_bottom).offset(-10).priorityHigh();
        make.left.equalTo(messageImg.mas_right).with.offset(10).priorityHigh();
        make.right.equalTo(messageView.mas_right).with.offset(-20).priorityHigh();
    }];
//    __weak typeof(self) weakSelf = self;
    WeakSelf(self);
    self.textCycle.clickItemOperationBlock = ^(NSInteger currentIndex) {
        weakself.hidesBottomBarWhenPushed=YES;
        HotNewsPageVC *sear=[[HotNewsPageVC alloc] init];
        [weakself.navigationController pushViewController:sear animated:YES];
        weakself.hidesBottomBarWhenPushed=NO;
    };
    [self.textCycle layoutIfNeeded];
    NSMutableArray *textArr=[[NSMutableArray alloc]init];
    for (DefaultModel *sModel in self.model.default_wap_hot_info)
    {
        [textArr addObject:sModel.title];
    }
    self.textCycle.titlesGroup =textArr;
    
    
    CountDownView *count=[[CountDownView alloc]init];
    [head addSubview:count];
    count.delegate=self;
    count.backgroundColor=[UIColor whiteColor];
    [count mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(head);
        make.height.offset(40);
        make.top.equalTo(messageView.mas_bottom).with.offset(10);
    }];
    [count layoutIfNeeded];
    
    SeckillView *kill=[[SeckillView alloc]init];
    kill.listArr=self.onsale;
    kill.delegate=self;
    [head addSubview:kill];
    [kill mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(head);
        make.height.offset(170);
        make.top.equalTo(count.mas_bottom).with.offset(0);
    }];
    [kill layoutIfNeeded];
    
    discount=[[HomeDiscountVIew alloc]init];
    [head addSubview:discount];
    discount.headView.image=[UIImage imageNamed:@"折扣区"];
    for (int i=0; i<self.adverArr.count; i++) {
        DefaultModel *model=self.adverArr[i];
        switch (i) {
            case 0:
                [discount.advertisement sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMGURL,model.pic]] placeholderImage:[UIImage imageNamed:@"图片空白页"]];
                break;
            case 1:
                [discount.groupBuying sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMGURL,model.pic]] placeholderImage:[UIImage imageNamed:@"图片空白页"]];
                break;
            case 2:
                [discount.auction sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMGURL,model.pic]] placeholderImage:[UIImage imageNamed:@"图片空白页"]];
                break;
            case 3:
                [discount.integral sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMGURL,model.pic]] placeholderImage:[UIImage imageNamed:@"图片空白页"]];
                break;

            default:
                break;
        }
    }
//    discount.advertisement.image=[UIImage imageNamed:@"广告1"];
//    discount.groupBuying.image=[UIImage imageNamed:@"团购专区"];
//    discount.auction.image=[UIImage imageNamed:@"拍卖疯抢"];
//    discount.integral.image=[UIImage imageNamed:@"积分惠"];
//
   
    discount.delegate=self;
    discount.tag=200;
    [discount mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(head);
        make.top.equalTo(kill.mas_bottom);
        make.height.offset(250);
    }];
    
    discount2=[[HomeDiscountVIew alloc]init];
    [head addSubview:discount2];
    discount2.headView.image=[UIImage imageNamed:@"精选区"];
    for (int i=0; i<self.adverArr.count; i++) {
        DefaultModel *model=self.adverArr[i];
        switch (i) {
            case 4:
                [discount2.advertisement sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMGURL,model.pic]] placeholderImage:[UIImage imageNamed:@"图片空白页"]];
                break;
            case 5:
                [discount2.groupBuying sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMGURL,model.pic]] placeholderImage:[UIImage imageNamed:@"图片空白页"]];
                break;
            case 6:
                [discount2.auction sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMGURL,model.pic]] placeholderImage:[UIImage imageNamed:@"图片空白页"]];
                break;
            case 7:
                [discount2.integral sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMGURL,model.pic]] placeholderImage:[UIImage imageNamed:@"图片空白页"]];
                break;
                
            default:
                break;
        }
    }
    discount2.delegate=self;
    discount2.tag=100;
    [discount2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(head);
        make.top.equalTo(discount.mas_bottom);
        make.height.offset(250);
      
    }];
    
    UIImageView *like=[[UIImageView alloc]init];
    like.image=[UIImage imageNamed:@"猜你喜欢"];
    [head addSubview:like];
    [like mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(discount2.mas_bottom);
        make.left.right.equalTo(head);
        make.height.offset(40);
        make.bottom.equalTo(head.mas_bottom).offset(0);
    }];
    
    height = [head systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
}

#pragma mark  DZNEmptyDataSetDelegate
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    if(self.emptyType==EmptyDataSetNoNetwork){
        return [UIImage imageNamed:@"断网"];
    }
    return nil;
}
- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView {
    if (self.emptyType==EmptyDataSetNone) {
        UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [activityView startAnimating];
        return activityView;
    }else{
        return nil;
    }
}
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    return NO;
}
- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return (STATUS_BAR_HEIGHT+44)/2;
}

- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n%@",Localized(@"您的网络不给力啊!"),Localized(@"请您检查是否联网。")]];
    [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:22],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#E6963F"]} range:NSMakeRange(0, [Localized(@"您的网络不给力啊!") length])];
    [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#C2AA93"]} range:NSMakeRange([Localized(@"您的网络不给力啊!") length], [Localized(@"请您检查是否联网。") length])];
    
    if(self.emptyType==EmptyDataSetNoNetwork){
        return currentPriceStr;
    }
    return nil;
}
- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state {
    NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:Localized(@"重新加载")];
    [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor whiteColor]} range:NSMakeRange(0, [Localized(@"重新加载") length])];
    
    if(self.emptyType==EmptyDataSetNoNetwork){
        return currentPriceStr;
    }
    return nil;
}

#pragma mark - DZNEmptyDataSetDelegate
- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button {
    [self loadDataWithIndex];
    self.hud=[MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow  animated:YES];
    self.hud.detailsLabel.text =  Localized(@"加载中...");
}
- (void)emptyDataSetWillAppear:(UIScrollView *)scrollView {
    self.collectionView.contentOffset = CGPointZero;
}

-(UICollectionView *)collectionView{
    if (!_collectionView) {
        //1.初始化layout
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        //设置collectionView滚动方向
        //    [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
        //2.初始化collectionView
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor groupTableViewBackgroundColor];
        
        //3.注册collectionViewCell
        //注意，此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致 均为 cellId
        [_collectionView registerClass:[HomeGoodsCell class] forCellWithReuseIdentifier:@"cell"];
        
        _collectionView.showsVerticalScrollIndicator=NO;
        //注册headerView  此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致  均为reusableView
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableView"];
        //4.设置代理
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.emptyDataSetSource = self;
        _collectionView.emptyDataSetDelegate = self;
    }
    return _collectionView;
}

-(NSMutableArray *)infoArr{
    if (!_infoArr) {
        _infoArr=[[NSMutableArray alloc] init];
    }
    return _infoArr;
}
-(NSMutableArray *)adverArr{
    if (!_adverArr) {
        _adverArr=[[NSMutableArray alloc] init];
    }
    return _adverArr;
}
-(NSMutableArray *)onsale{
    if (!_onsale) {
        _onsale=[[NSMutableArray alloc] init];
    }
    return _onsale;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
